package edu.uic.kott.activities;

import java.util.List;

import edu.uic.keyoutcomestrackertool.R;
import edu.uic.kott.db.KottDataSource;
import edu.uic.kott.model.ClassActivity;
import android.app.ListActivity;
import android.content.Intent;
import android.os.Bundle;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.ArrayAdapter;
import android.widget.ListView;
import android.widget.Toast;

public class CourseActivities extends ListActivity {

	private static final String LOGTAG = "KOTT";

	KottDataSource datasource; 

	List<ClassActivity> allActivities;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.course_activities);

		datasource = new KottDataSource(this);
	}
	public void refreshDisplay(String sort){
		Toast msg;
		if("date".equalsIgnoreCase(sort)){
			allActivities = datasource.findAllActivities("date");
			msg = Toast.makeText(this, "SORTED BY DATE", Toast.LENGTH_SHORT);
			msg.show();
		}
		if("class".equalsIgnoreCase(sort)){
			allActivities = datasource.findAllActivities("class");
			msg = Toast.makeText(this, "SORTED BY CLASS", Toast.LENGTH_SHORT);
			msg.show();
		}

		if(allActivities.size() > 0){	
			ArrayAdapter<ClassActivity> allActivitiesAdapter = new ArrayAdapter<ClassActivity>(this, android.R.layout.simple_list_item_1, allActivities);
			setListAdapter(allActivitiesAdapter);
		}
		else{
			Log.i(LOGTAG, "No activities added!");
		}
	}

	@Override
	protected void onListItemClick(ListView l, View v, int position, long id) {
		super.onListItemClick(l, v, position, id);

		ClassActivity acvty = allActivities.get(position);		

		Log.i(LOGTAG, acvty.getActivityName() + " clicked");

		Intent intent = new Intent(this, ActivityDetails.class);
		intent.putExtra("activityId", String.valueOf(acvty.getActivityId()));
		startActivity(intent);
	}


	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		getMenuInflater().inflate(R.menu.menu_sort_add, menu);		
		return true;
	}

	@Override
	public boolean onOptionsItemSelected(MenuItem item) {
		if(item.getOrder() == 100)
		{
			refreshDisplay("date");						
		}
		if(item.getOrder() == 101){
			refreshDisplay("class");
		}
		if(item.getOrder() == 102)
		{
			startActivity(new Intent(CourseActivities.this, AddEditActivity.class));
		}


		return super.onOptionsItemSelected(item);
	}
	@Override
	protected void onResume() {
		refreshDisplay("date");
		super.onResume();
	}

}
